package user

import (
	"context"
	"errors"
	"go-zero-all-demos/apps/user/rpc/userservice"
	"go-zero-all-demos/pkg/auth"

	"go-zero-all-demos/apps/api/internal/svc"
	"go-zero-all-demos/apps/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.UserInfo) (resp *types.TokenResponse, err error) {
	user, err := l.svcCtx.UserRPC.GetUserByNameAndPassword(
		l.ctx,
		&userservice.NameAndPasswordRequest{Name: req.Name, Password: req.Password,
		})
	if err != nil {
		return nil, err
	}
	if user == nil || user.Id == 0 {
		return nil, errors.New("invalid user")
	}

	token, err := auth.GenerateJWTToken(user.Id, l.svcCtx.Config.Auth.AccessSecret, l.svcCtx.Config.Auth.AccessExpire)
	if err != nil {
		return nil, err
	}
	return &types.TokenResponse{Token: token}, nil
}
